"""
This program extract IoT malware sample information for the dataset of IoT-IPS.
"""

import csv
import traceback
from tools import Tools
from mispconn.utils import CFG
from datetime import datetime

CSV_PATH = '/home/samsung/IoT-IPS/results/ds_stats/malware_info.csv'

misp = Tools.init_misp(url=CFG['misp']['url'], key=CFG['misp']['key'])

samples = []
for i in range(238545, 239551):
    try:
        event = misp.get_event(i)['Event']
        if 'IoT malware' not in event['info']:
            continue
        event_id = event['id']
        print(event_id)
        honeypot = event['event_creator_email']
        timestamp = datetime.utcfromtimestamp(int(event['timestamp'])).strftime('%Y-%m-%d %H:%M:%S')
        file_type = None
        processor = None
        for tag in event['Tag']:
            if 'file-type' in tag['name']:
                temp_file_type = tag['name'].split('="')[1].strip('"')
                if len(temp_file_type) == '1' or temp_file_type == 'html':
                    continue    # html
                if file_type is None:
                    file_type = temp_file_type
                elif len(file_type) < len(temp_file_type):
                    file_type = temp_file_type
            elif 'processor' in tag['name']:
                processor = tag['name'].split('="')[1].strip('"')
        samples.append([event_id, timestamp, file_type, processor, honeypot])
    except:
        traceback.print_exc()

    with open(CSV_PATH, "w") as f:
        csv_writer = csv.writer(f)
        table_title = ['event_id', 'datetime', 'file-type', 'processor', 'honeypot']
        csv_writer.writerow(table_title)
        csv_writer.writerows(samples)
print('Done!')